#include "Common.h"

CombatHandler::CombatHandler(Unit* m_unit) : m_pbelonging(m_unit), m_target(0), m_lastupdate(0), m_attackrate(1500)
{
}

void CombatHandler::EventCombatStart(Unit* pVictim)
{
	if(!m_pbelonging)
		return;
	if(pVictim->IsCreature())
	{
		Creature* c = (Creature*)pVictim;
		CALL_CREATURE_SCRIPT(c, OnCombatStart)(m_pbelonging);
		c->GetCreatureAI().UnitEnteredCombat(m_pbelonging);
	}
	m_combat = true;
	m_target = pVictim;
	RealmPacket data(SMSG_ATTACKSTART);
	data << m_pbelonging->GetGUID() << pVictim->GetGUID();
	if(m_pbelonging->IsPlayer())
		((Player*)m_pbelonging)->GetSession()->SendToSet(&data, true);
}

void CombatHandler::EventCombatEnd()
{
	if(!m_target)
		return;
	RealmPacket data(SMSG_ATTACKSTOP);
	if(m_pbelonging->IsPlayer())
	{
		data << m_target->GetNewGUID();
		data << ui8(0) << ui32(0);
		((Player*)m_pbelonging)->GetSession()->SendPacket(&data);
		data.Clear();
		data.SetOpcode(SMSG_ATTACKSTOP);
	}
	data << m_pbelonging->GetNewGUID();
	data << m_target->GetNewGUID();
	data << ui32(0);
	if(m_pbelonging->IsPlayer())
	{
		((Player*)m_pbelonging)->GetSession()->SendToSet(&data, true);
	}
	m_target = 0;
	m_combat = false;
}

void CombatHandler::Update()
{
	if(GetTickCount() - m_lastupdate < m_attackrate)
		return;
	if(IsInCombat())
		UpdateAttackState();
	m_lastupdate = GetTickCount();
}

void CombatHandler::UpdateAttackState()
{
	if(!m_pbelonging || !m_target)
		return;
	RealmPacket data(SMSG_ATTACKERSTATEUPDATE);
	data << ui32(0x02);
	data << m_pbelonging->GetNewGUID();
	data << m_target->GetNewGUID();
	data << ui32(150);
	data << ui32(0);
	data << ui8(1);
	data << ui32(1);
	data << float(1500);
	data << ui32(1500);
	data << ui8(1);
	data << ui32(0x3e8);
	data << ui32(0);
	if(m_pbelonging->IsPlayer())
	{
		((Player*)m_pbelonging)->GetSession()->SendToSet(&data, true);
	}
	else
		m_pbelonging->SendToSet(data);
}